package com.divemotor.ventarepuestosinternet.util.converter;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.divemotor.ventarepuestosinternet.model.Sucursal;
import com.divemotor.ventarepuestosinternet.service.SucursalService;
import com.divemotor.ventarepuestosinternet.util.Constantes;



@Component("sucursalConverter")
public class SucursalConverter implements Converter {

	@Autowired
	SucursalService sucursalService;
	
	@Override
	public Object getAsObject(FacesContext facesContext, UIComponent component, String submittedValue) {
		if (submittedValue.trim().equals("")) {
            return null;
        } else {
            try {
            	
            	if (submittedValue.equals(Constantes.NO_SELECCIONADO.toString())) {
            		return new Sucursal(Constantes.NO_SELECCIONADO,
            				Constantes.NO_SELECCIONADO_ETIQUETA);
            	} else {
            		Sucursal sucursal = sucursalService.obtenerSucursalPorId(new Sucursal(new Integer(submittedValue),""));
                    return sucursal;
				}

            } catch(Exception exception) {
                throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error", "No es una sucursal valida"));
            }
        }

        
	}

	@Override
	public String getAsString(FacesContext facesContext, UIComponent component, Object value) {
		if (value == null) {
            return null;
        } else {
            return ((Sucursal) value).getIdSucursal().toString();
        }
		
		
	}

}
